package fr.mywiki.business.wiki.render;

import java.util.Locale;
import java.util.MissingResourceException;

import org.radeox.api.engine.RenderEngine;
import org.radeox.api.engine.context.InitialRenderContext;
import org.radeox.api.engine.context.RenderContext;
import org.radeox.engine.BaseRenderEngine;
import org.radeox.engine.context.BaseInitialRenderContext;

import fr.mywiki.business.log.LogManager;

/** Render engine for wiki language. Uses Radeox API */
public class WikiRenderEngine {
	public static final String LOCALE_NAME = "mywiki";
	public static final String BUNDLE_NAME = "radeox_markup_" + LOCALE_NAME;

	private WikiRenderEngine() {}

	/**
	 * The render engine is kept in application. Maybe later it will be useful to keep it in
	 * session...
	 */
	private static RenderEngine engine;

	/**
	 * The initial render context is kept in application.
	 */
	private static InitialRenderContext context;

	/** The regex for line delimitation in html */
	public static final String LINE_DELIM_REGEX = "\r\n";
	
	/**
	 * Returns the <code>RenderEngine</code> object which is to be used.
	 */
	private static RenderEngine getRenderEngine() {
		if (engine == null) {
			loadEngine();
		}
		return engine;
	}

	/**
	 * Returns the <code>InitialRenderContext</code> object which is to be used.
	 */
	private static InitialRenderContext getContext() {
		if (context == null) {
			loadEngine();
		}
		return context;
	}

	/** Loads the render engine */
	private static void loadEngine() {
		context = new BaseInitialRenderContext();

		Locale languageLocale = Locale.getDefault();
		Locale locale = new Locale(LOCALE_NAME, LOCALE_NAME);
		context.set(RenderContext.INPUT_LOCALE, locale);
		context.set(RenderContext.OUTPUT_LOCALE, locale);
		context.set(RenderContext.LANGUAGE_LOCALE, languageLocale);
		context.set(RenderContext.INPUT_BUNDLE_NAME, BUNDLE_NAME);
		context.set(RenderContext.OUTPUT_BUNDLE_NAME, BUNDLE_NAME);
		context.set(RenderContext.LANGUAGE_BUNDLE_NAME, BUNDLE_NAME);

		engine = new BaseRenderEngine(context);
	}

	public static String render(String wikiText) {
		StringBuffer buffer = new StringBuffer("<div>");
		try {
			long before = System.currentTimeMillis();
			buffer.append(getRenderEngine().render(wikiText, getContext()));
			long after = System.currentTimeMillis();
			long timeSecond = (after-before)/1000;
			LogManager.println("Rendering time : " + timeSecond);
		} catch (MissingResourceException e) {
		}
		return buffer.append("</div>").toString();
	}
}
